<template>
	<div class="form-item-select">
		<van-field :label="label" :required="required" :model-value="currText" :readonly="readonly" @click="open" :disabled="disabled" />
		<van-popup v-model:show="show" position="top">
			<div class="select-list">
				<div class="select-item" v-for="item in optionList" :key="item.value" @click="confirm(item)">
					<div class="text">{{ item.text }}</div>
					<van-icon v-if="modelValue === item.value" name="success" color="red" />
				</div>
			</div>
		</van-popup>
	</div>
</template>

<script>
import { ref, watch, onMounted } from 'vue'
import { getDic } from '@/api'
export default {
	name: 'FormItemSelect',
	props: {
		modelValue: { type: String, default: '' },
		itemKey: { type: String, default: '' },
		label: { type: String, default: '' },
		required: { type: Boolean, default: false },
		disabled: { type: Boolean, default: false },
		readonly: { type: Boolean, default: false },
		dicKey: { type: String, default: '' },
		optionList: { type: Array, default: () => [] },
	},
	emits: ['update:modelValue', 'selected', 'change'],
	setup(props, { emit }) {
		const show = ref(false)
		const innerOptions = ref([...props.optionList])
		const currText = ref('')

		const initDic = async () => {
			if (!props.dicKey) return
			try {
				const data = await getDic(props.dicKey)
				innerOptions.value = data.map((d) => ({ text: d.dictLabel, value: d.dictValue, detail: d }))
			} catch (e) {
				console.error('获取字典失败', e)
			}
		}

		const syncText = () => {
			const target = [...innerOptions.value, ...props.optionList].find((o) => o.value === props.modelValue)
			currText.value = target ? target.text : ''
		}

		watch(() => props.modelValue, syncText)
		watch(
			() => props.optionList,
			(nv) => {
				if (nv.length) {
					innerOptions.value = nv
					syncText()
				}
			}
		)

		const open = () => {
			if (props.disabled || props.readonly) return
			if (innerOptions.value.length === 0) {
				currText.value = ''
				return
			}
			show.value = true
		}
		const close = () => {
			show.value = false
		}
		const confirm = (item) => {
			emit('update:modelValue', item.value)
			emit('selected', { data: item })
			emit('change', { [props.itemKey]: item.value })
			close()
			syncText()
		}
		onMounted(() => {
			initDic()
			syncText()
		})
		return { show, optionList: innerOptions, currText, open, close, confirm }
	},
}
</script>

<style lang="less" scoped>
.select-list {
	padding: 8px;
}
.select-item {
	display: flex;
	align-items: center;
	border-bottom: 1px solid #d7d7d7;
	padding: 6px 4px;
}
.text {
	flex: 1;
}
</style>